$(function () {
    $('.links').on('click', function () {
        $(this).parents('.login-box').hide();
        $(this).parents('.login-box').siblings('.reg-box').show();
    });
    $('#link_login').on('click', function () {
        $(this).parents('.reg-box').hide();
        $(this).parents('.reg-box').siblings('.login-box').show();
    });

    var form = layui.form;
    var layer = layui.layer;
    form.verify({
        pwd: [
            /^[\S]{6,12}$/,
            '密码长度6-12位，且不能包含空格'
        ],
        repwd: function (value) {
            // 判断两次输入的密码是否相等
            var pwd = $('.reg-box [name=password]').val();
            if (value !== pwd) {
                return "两次输入密码不一致";
            }
        }
    });

    $('#form_reg').on('submit', function (e) {
        e.preventDefault();

        $.post('/api/reguser', {
            username: $('#form_reg [name=username]').val(),
            password: $('#form_reg [name=password]').val()
        }, function (res) {
            if (res.status !== 0) {
                return layer.msg(res.message);
            }
            layer.msg('注册成功，请登录！');
            $('#link_login').click();
        });
    });
    $('#form_login').on('submit', function (e) {
        e.preventDefault();

        $.ajax({
            method: 'POST',
            url: '/api/login',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg(res.message);
                }
                layer.msg('登录成功！');
                localStorage.setItem('token', res.token);
                location.href = '/index.html';
            }
        });
    });
});